/**
 * 活动效果评估页面JavaScript
 * 基于Apple Design System的交互设计
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let currentSection = 'data-analysis';
let evaluationData = {};
let followUpTasks = [];
let surveyData = {};

// DOM 元素
const evaluationSteps = document.querySelectorAll('.nav-step');
const evaluationContents = document.querySelectorAll('.evaluation-content');
const filterTabs = document.querySelectorAll('.filter-tab');

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    loadEvaluationData();
    loadFollowUpTasks();
    loadSurveyData();
    updateDisplays();
    handleUrlParameters();
});

// 初始化事件监听器
function initializeEventListeners() {
    // 评估阶段切换
    evaluationSteps.forEach(step => {
        step.addEventListener('click', () => {
            switchEvaluationSection(step.dataset.step);
        });
    });
    
    // 跟进筛选切换
    filterTabs.forEach(tab => {
        tab.addEventListener('click', () => {
            switchFollowUpFilter(tab.dataset.filter);
        });
    });
    
    // 通用事件
    document.addEventListener('keydown', handleKeyDown);
}

// 切换评估部分
function switchEvaluationSection(section) {
    currentSection = section;
    
    // 更新导航状态
    evaluationSteps.forEach(step => {
        step.classList.toggle('active', step.dataset.step === section);
    });
    
    // 显示对应内容
    evaluationContents.forEach(content => {
        if (content.id === `${section}-content`) {
            content.style.display = 'block';
        } else {
            content.style.display = 'none';
        }
    });
    
    // 特殊处理
    if (section === 'follow-up') {
        updateFollowUpDisplay();
    }
}

// 切换跟进筛选
function switchFollowUpFilter(filter) {
    // 更新筛选状态
    filterTabs.forEach(tab => {
        tab.classList.toggle('active', tab.dataset.filter === filter);
    });
    
    // 筛选跟进任务
    filterFollowUpTasks(filter);
}

// 加载评估数据
function loadEvaluationData() {
    // 模拟评估数据
    evaluationData = {
        activityId: 'ACT2025000001',
        activityName: '桂林山水3日游邀约活动',
        activityDate: '2025-07-25',
        metrics: {
            invitedCount: 30,
            participatedCount: 23,
            participationRate: 76.7,
            satisfactionRate: 87.0,
            intentionRate: 34.8,
            estimatedRevenue: 32500
        },
        costs: {
            venue: 800,
            equipment: 400,
            refreshments: 600,
            materials: 300,
            staff: 1200,
            total: 3300
        },
        benefits: {
            shortTerm: 18000,
            mediumTerm: 14500,
            referrals: 8500,
            total: 41000
        },
        participationBreakdown: {
            onTime: 18,
            late: 5,
            absent: 4,
            declined: 3
        },
        demographics: {
            age: {
                '55-65': 8,
                '66-75': 12,
                '76+': 3
            },
            region: {
                'local': 19,
                'nearby': 4
            },
            customerType: {
                'vip': 6,
                'existing': 10,
                'new': 7
            }
        },
        timeAnalysis: [
            {
                time: '14:30-14:45',
                title: '开场介绍',
                participation: 95,
                engagement: '高'
            },
            {
                time: '14:45-15:30',
                title: '产品展示',
                participation: 89,
                engagement: '高'
            },
            {
                time: '15:30-16:00',
                title: '互动问答',
                participation: 78,
                engagement: '中'
            },
            {
                time: '16:00-16:30',
                title: '咨询签约',
                participation: 65,
                engagement: '高'
            }
        ]
    };
}

// 加载跟进任务
function loadFollowUpTasks() {
    followUpTasks = [
        {
            id: 1,
            customerId: 'CRM2025000001',
            customerName: '张大爷',
            customerAge: 68,
            customerType: 'VIP客户',
            customerRegion: '本市',
            priority: 'urgent',
            title: '电话跟进确认意向',
            description: '客户在活动中表现出强烈兴趣，需要尽快跟进确认具体需求',
            scheduledTime: '2025-07-26 09:00',
            status: 'overdue',
            tags: ['高意向', '电话跟进'],
            opportunityValue: 6000
        },
        {
            id: 2,
            customerId: 'CRM2025000002',
            customerName: '李大妈',
            customerAge: 65,
            customerType: '优质客户',
            customerRegion: '本市',
            priority: 'high',
            title: '提供云南线路方案',
            description: '客户对云南旅游线路感兴趣，需要制定专门的旅游方案',
            scheduledTime: '2025-07-27 14:00',
            status: 'upcoming',
            tags: ['高意向', '方案制定'],
            opportunityValue: 7250
        },
        {
            id: 3,
            customerId: 'CRM2025000003',
            customerName: '王阿姨',
            customerAge: 72,
            customerType: '普通客户',
            customerRegion: '邻近城市',
            priority: 'normal',
            title: '关怀回访',
            description: '客户提出了一些建议，需要回访表示感谢并了解进一步需求',
            scheduledTime: '2025-07-28 10:00',
            status: 'scheduled',
            tags: ['一般关注', '电话回访'],
            opportunityValue: 4500
        }
    ];
}

// 加载调查数据
function loadSurveyData() {
    surveyData = {
        totalResponses: 23,
        overallSatisfaction: 87,
        satisfactionBreakdown: {
            verySatisfied: 12,
            satisfied: 8,
            neutral: 3,
            dissatisfied: 0,
            veryDissatisfied: 0
        },
        serviceRatings: {
            organization: 4.6,
            professionalism: 4.2,
            venue: 4.8,
            refreshments: 4.1
        },
        feedbacks: [
            {
                id: 1,
                customerName: '张大爷',
                type: 'positive',
                content: '活动组织得很好，讲解很专业，桂林的风景确实很吸引人。价格也比较合理，我和老伴都很感兴趣。',
                time: '2025-07-25 17:30',
                rating: 5
            },
            {
                id: 2,
                customerName: '李大妈',
                type: 'positive',
                content: '服务态度很好，茶点也不错。不过希望能提供更多的线路选择，我们比较想去云南。',
                time: '2025-07-25 18:15',
                rating: 4
            },
            {
                id: 3,
                customerName: '王阿姨',
                type: 'neutral',
                content: '活动时间有点长，建议缩短一些。另外希望能提供更多的互动环节，让大家更好地交流。',
                time: '2025-07-25 19:00',
                rating: 3
            }
        ]
    };
}

// 更新显示
function updateDisplays() {
    updateMetricsDisplay();
    updateAnalysisDisplay();
    updateCostBenefitDisplay();
    updateSatisfactionDisplay();
    updateFollowUpDisplay();
}

// 更新指标显示
function updateMetricsDisplay() {
    const metrics = evaluationData.metrics;
    
    // 更新核心指标
    updateMetricCard(0, metrics.participationRate.toFixed(1) + '%', `${metrics.participatedCount}人参与 / ${metrics.invitedCount}人邀请`);
    updateMetricCard(1, metrics.satisfactionRate + '%', `${Math.round(metrics.participatedCount * metrics.satisfactionRate / 100)}人满意 / ${metrics.participatedCount}人参与`);
    updateMetricCard(2, metrics.intentionRate.toFixed(1) + '%', `${Math.round(metrics.participatedCount * metrics.intentionRate / 100)}人有意向 / ${metrics.participatedCount}人参与`);
    updateMetricCard(3, '¥' + metrics.estimatedRevenue.toLocaleString(), '基于意向客户预估');
}

// 更新指标卡片
function updateMetricCard(index, number, detail) {
    const cards = document.querySelectorAll('.metric-card');
    if (cards[index]) {
        const numberEl = cards[index].querySelector('.metric-number');
        const detailEl = cards[index].querySelector('.metric-detail');
        if (numberEl) numberEl.textContent = number;
        if (detailEl) detailEl.textContent = detail;
    }
}

// 更新分析显示
function updateAnalysisDisplay() {
    updateParticipationBreakdown();
    updateDemographicStats();
    updateTimelineAnalysis();
}

// 更新参与情况分解
function updateParticipationBreakdown() {
    const breakdown = evaluationData.participationBreakdown;
    const total = evaluationData.metrics.invitedCount;
    
    const items = document.querySelectorAll('.breakdown-item');
    const data = [
        { label: '按时到达', value: breakdown.onTime, total: evaluationData.metrics.participatedCount },
        { label: '迟到参与', value: breakdown.late, total: evaluationData.metrics.participatedCount },
        { label: '临时缺席', value: breakdown.absent, total: total },
        { label: '提前拒绝', value: breakdown.declined, total: total }
    ];
    
    items.forEach((item, index) => {
        if (data[index]) {
            const percentage = ((data[index].value / data[index].total) * 100).toFixed(1);
            const valueEl = item.querySelector('.breakdown-value');
            const barEl = item.querySelector('.bar-fill');
            
            if (valueEl) valueEl.textContent = `${data[index].value}人 (${percentage}%)`;
            if (barEl) barEl.style.width = percentage + '%';
        }
    });
}

// 更新人群统计
function updateDemographicStats() {
    const demographics = evaluationData.demographics;
    
    // 这里可以根据需要更新人群统计显示
    // 当前静态显示已经包含了基本信息
}

// 更新时间线分析
function updateTimelineAnalysis() {
    const timeAnalysis = evaluationData.timeAnalysis;
    
    // 这里可以根据需要更新时间线分析显示
    // 当前静态显示已经包含了基本信息
}

// 更新成本效益显示
function updateCostBenefitDisplay() {
    const costs = evaluationData.costs;
    const benefits = evaluationData.benefits;
    
    // 更新成本项目
    const costItems = document.querySelectorAll('.cost-item');
    const costData = [
        { label: '场地租赁', value: costs.venue },
        { label: '设备租赁', value: costs.equipment },
        { label: '茶点费用', value: costs.refreshments },
        { label: '宣传材料', value: costs.materials },
        { label: '人员成本', value: costs.staff },
        { label: '总成本', value: costs.total }
    ];
    
    costItems.forEach((item, index) => {
        if (costData[index]) {
            const valueEl = item.querySelector('.cost-value');
            if (valueEl) valueEl.textContent = '¥' + costData[index].value.toLocaleString();
        }
    });
    
    // 更新收益项目
    const benefitItems = document.querySelectorAll('.benefit-item');
    const benefitData = [
        { label: '短期签约 (30天内)', value: benefits.shortTerm },
        { label: '中期签约 (3个月内)', value: benefits.mediumTerm },
        { label: '后续推荐', value: benefits.referrals },
        { label: '预期总收益', value: benefits.total }
    ];
    
    benefitItems.forEach((item, index) => {
        if (benefitData[index]) {
            const valueEl = item.querySelector('.benefit-value');
            if (valueEl) valueEl.textContent = '¥' + benefitData[index].value.toLocaleString();
        }
    });
    
    // 更新ROI
    const roi = ((benefits.total - costs.total) / costs.total * 100).toFixed(0);
    const acquisitionCost = Math.round(costs.total / evaluationData.metrics.participatedCount);
    
    const roiItems = document.querySelectorAll('.roi-item');
    if (roiItems[0]) {
        const roiValue = roiItems[0].querySelector('.roi-value');
        if (roiValue) roiValue.textContent = roi + '%';
    }
    if (roiItems[1]) {
        const costValue = roiItems[1].querySelector('.roi-value');
        if (costValue) costValue.textContent = '¥' + acquisitionCost + '/人';
    }
}

// 更新满意度显示
function updateSatisfactionDisplay() {
    const survey = surveyData;
    
    // 更新整体满意度
    const scoreEl = document.querySelector('.satisfaction-score');
    if (scoreEl) scoreEl.textContent = survey.overallSatisfaction + '%';
    
    // 更新满意度分解
    const satisfactionItems = document.querySelectorAll('.satisfaction-item');
    const breakdownData = [
        { label: '非常满意', value: survey.satisfactionBreakdown.verySatisfied },
        { label: '满意', value: survey.satisfactionBreakdown.satisfied },
        { label: '一般', value: survey.satisfactionBreakdown.neutral }
    ];
    
    satisfactionItems.forEach((item, index) => {
        if (breakdownData[index]) {
            const percentage = Math.round((breakdownData[index].value / survey.totalResponses) * 100);
            const barEl = item.querySelector('.bar-fill');
            const labelEl = item.querySelector('.bar-label');
            
            if (barEl) barEl.style.width = percentage + '%';
            if (labelEl) labelEl.textContent = `${breakdownData[index].value}人 (${percentage}%)`;
        }
    });
    
    // 更新服务评分
    const ratingItems = document.querySelectorAll('.rating-item');
    const ratingData = [
        { label: '活动组织', score: survey.serviceRatings.organization },
        { label: '讲解专业度', score: survey.serviceRatings.professionalism },
        { label: '场地环境', score: survey.serviceRatings.venue },
        { label: '茶点服务', score: survey.serviceRatings.refreshments }
    ];
    
    ratingItems.forEach((item, index) => {
        if (ratingData[index]) {
            const scoreEl = item.querySelector('.rating-score');
            if (scoreEl) scoreEl.textContent = ratingData[index].score + '分';
            
            // 更新星级显示
            updateStarRating(item, ratingData[index].score);
        }
    });
}

// 更新星级评分
function updateStarRating(item, score) {
    const starsContainer = item.querySelector('.rating-stars');
    if (!starsContainer) return;
    
    const stars = starsContainer.querySelectorAll('i');
    const fullStars = Math.floor(score);
    const hasHalfStar = score % 1 >= 0.5;
    
    stars.forEach((star, index) => {
        star.className = 'fas fa-star'; // 重置
        
        if (index < fullStars) {
            star.className = 'fas fa-star';
        } else if (index === fullStars && hasHalfStar) {
            star.className = 'fas fa-star-half-alt';
        } else {
            star.className = 'far fa-star';
        }
    });
}

// 更新跟进显示
function updateFollowUpDisplay() {
    updateFollowUpStats();
    renderFollowUpList('all');
    updateConversionPipeline();
}

// 更新跟进统计
function updateFollowUpStats() {
    const stats = {
        total: followUpTasks.length,
        today: followUpTasks.filter(task => isToday(task.scheduledTime)).length,
        highIntent: followUpTasks.filter(task => task.tags.includes('高意向')).length,
        completed: followUpTasks.filter(task => task.status === 'completed').length
    };
    
    const statCards = document.querySelectorAll('.followup-stat');
    const statData = [stats.total, stats.today, stats.highIntent, stats.completed];
    
    statCards.forEach((card, index) => {
        const numberEl = card.querySelector('.stat-number');
        if (numberEl && statData[index] !== undefined) {
            numberEl.textContent = statData[index];
        }
    });
}

// 渲染跟进列表
function renderFollowUpList(filter) {
    const filteredTasks = filterFollowUpTasks(filter);
    const container = document.querySelector('.followup-list');
    
    if (!container) return;
    
    container.innerHTML = '';
    
    filteredTasks.forEach(task => {
        const taskEl = createFollowUpItem(task);
        container.appendChild(taskEl);
    });
}

// 创建跟进项目
function createFollowUpItem(task) {
    const item = document.createElement('div');
    item.className = `followup-item ${task.priority}`;
    item.dataset.taskId = task.id;
    
    const priorityIcon = getPriorityIcon(task.priority);
    const statusClass = getStatusClass(task.status);
    const statusText = getStatusText(task.status);
    
    item.innerHTML = `
        <div class="followup-priority">
            <i class="${priorityIcon}"></i>
        </div>
        <div class="followup-customer">
            <div class="customer-avatar">${task.customerName.charAt(0)}</div>
            <div class="customer-info">
                <div class="customer-name">${task.customerName}</div>
                <div class="customer-detail">${task.customerAge}岁 | ${task.customerType} | ${task.customerRegion}</div>
            </div>
        </div>
        <div class="followup-content">
            <div class="followup-title">${task.title}</div>
            <div class="followup-desc">${task.description}</div>
            <div class="followup-tags">
                ${task.tags.map(tag => `<span class="tag tag-${getTagClass(tag)}">${tag}</span>`).join('')}
            </div>
        </div>
        <div class="followup-schedule">
            <div class="schedule-time">
                <i class="fas fa-clock"></i>
                ${formatScheduleTime(task.scheduledTime)}
            </div>
            <div class="schedule-status ${statusClass}">${statusText}</div>
        </div>
        <div class="followup-actions">
            <button class="action-btn primary" onclick="executeFollowUp(${task.id})">
                <i class="${getActionIcon(task)}"></i>
            </button>
            <button class="action-btn" onclick="editFollowUp(${task.id})">
                <i class="fas fa-edit"></i>
            </button>
            <button class="action-btn" onclick="completeFollowUp(${task.id})">
                <i class="fas fa-check"></i>
            </button>
        </div>
    `;
    
    return item;
}

// 筛选跟进任务
function filterFollowUpTasks(filter) {
    switch (filter) {
        case 'urgent':
            return followUpTasks.filter(task => task.priority === 'urgent' || task.status === 'overdue');
        case 'high-intent':
            return followUpTasks.filter(task => task.tags.includes('高意向'));
        case 'completed':
            return followUpTasks.filter(task => task.status === 'completed');
        default:
            return followUpTasks;
    }
}

// 更新转化漏斗
function updateConversionPipeline() {
    // 这里可以根据实际数据更新转化漏斗显示
    // 当前静态显示已经包含了基本信息
}

// 工具函数
function isToday(dateString) {
    const today = new Date();
    const date = new Date(dateString);
    return date.toDateString() === today.toDateString();
}

function getPriorityIcon(priority) {
    const iconMap = {
        'urgent': 'fas fa-exclamation-circle',
        'high': 'fas fa-star',
        'normal': 'fas fa-circle',
        'low': 'fas fa-minus'
    };
    return iconMap[priority] || 'fas fa-circle';
}

function getStatusClass(status) {
    const classMap = {
        'overdue': 'overdue',
        'upcoming': 'upcoming',
        'scheduled': 'scheduled',
        'completed': 'completed'
    };
    return classMap[status] || 'scheduled';
}

function getStatusText(status) {
    const textMap = {
        'overdue': '已逾期',
        'upcoming': '待执行',
        'scheduled': '已安排',
        'completed': '已完成'
    };
    return textMap[status] || '未知';
}

function getTagClass(tag) {
    if (tag.includes('高意向')) return 'high-intent';
    if (tag.includes('一般')) return 'normal';
    return 'method';
}

function getActionIcon(task) {
    if (task.title.includes('电话')) return 'fas fa-phone';
    if (task.title.includes('方案')) return 'fas fa-file-alt';
    if (task.title.includes('回访')) return 'fas fa-phone';
    return 'fas fa-play';
}

function formatScheduleTime(dateString) {
    const date = new Date(dateString);
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const dateStr = date.toDateString();
    const todayStr = today.toDateString();
    const tomorrowStr = tomorrow.toDateString();
    
    let dayText;
    if (dateStr === todayStr) {
        dayText = '今天';
    } else if (dateStr === tomorrowStr) {
        dayText = '明天';
    } else {
        dayText = '后天';
    }
    
    const timeStr = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    return `${dayText} ${timeStr}`;
}

// 导出和分享函数
function generateReport() {
    showNotification('正在生成评估报告...', 'info');
    // 这里实现报告生成逻辑
    setTimeout(() => {
        showNotification('评估报告生成完成', 'success');
    }, 2000);
}

function exportSummary() {
    showNotification('正在导出活动总结...', 'info');
    // 这里实现总结导出逻辑
    setTimeout(() => {
        showNotification('活动总结导出完成', 'success');
    }, 2000);
}

function sendSurvey() {
    showNotification('正在发送满意度调查...', 'info');
    // 这里实现调查发送逻辑
    setTimeout(() => {
        showNotification('满意度调查已发送', 'success');
    }, 1500);
}

// 跟进任务管理函数
function createFollowUpTask() {
    showNotification('创建跟进任务功能正在开发中...', 'info');
}

function executeFollowUp(taskId) {
    const task = followUpTasks.find(t => t.id === taskId);
    if (!task) return;
    
    showNotification(`正在执行跟进任务：${task.title}`, 'info');
    // 这里实现执行跟进逻辑
}

function editFollowUp(taskId) {
    const task = followUpTasks.find(t => t.id === taskId);
    if (!task) return;
    
    showNotification('编辑跟进任务功能正在开发中...', 'info');
}

function completeFollowUp(taskId) {
    const task = followUpTasks.find(t => t.id === taskId);
    if (!task) return;
    
    if (confirm(`确定要完成跟进任务"${task.title}"吗？`)) {
        task.status = 'completed';
        updateFollowUpDisplay();
        showNotification('跟进任务已完成', 'success');
    }
}

function loadMoreFollowUps() {
    showNotification('加载更多跟进任务功能正在开发中...', 'info');
}

function createSalesOpportunity() {
    showNotification('创建销售机会功能正在开发中...', 'info');
}

function goBackToActivity() {
    window.location.href = 'invitation-management.html';
}

// 处理URL参数
function handleUrlParameters() {
    const urlParams = new URLSearchParams(window.location.search);
    const activityId = urlParams.get('activityId');
    const section = urlParams.get('section');
    
    // 如果有活动ID，可以根据ID加载对应的活动数据
    if (activityId) {
        console.log('Activity ID:', activityId);
        // 这里可以调用API获取特定活动的评估数据
        loadActivityEvaluationData(activityId);
    }
    
    // 如果指定了section，自动切换到对应模块
    if (section && ['data-analysis', 'customer-feedback', 'follow-up', 'improvement'].includes(section)) {
        switchEvaluationSection(section);
    }
}

// 根据活动ID加载评估数据
function loadActivityEvaluationData(activityId) {
    // 模拟根据活动ID加载不同的数据
    console.log('Loading evaluation data for activity:', activityId);
    
    // 这里可以发送AJAX请求获取真实数据
    // 现在使用模拟数据
    if (activityId !== 'ACT2025000001') {
        // 可以根据不同活动ID返回不同的数据
        evaluationData.activityName = `活动${activityId}的效果评估`;
    }
    
    // 更新页面标题和活动信息
    updateActivityInfo();
}

// 更新活动信息显示
function updateActivityInfo() {
    const activityNameEl = document.querySelector('.activity-name');
    if (activityNameEl && evaluationData.activityName) {
        activityNameEl.textContent = evaluationData.activityName;
    }
}

// 通用函数
function handleKeyDown(event) {
    if (event.key === 'Escape') {
        // 处理ESC键逻辑
    }
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${getNotificationIcon(type)}"></i>
        <span>${message}</span>
    `;
    
    document.body.appendChild(notification);
    
    notification.style.position = 'fixed';
    notification.style.top = '80px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.minWidth = '300px';
    notification.style.animation = 'slideInRight 0.3s ease-out';
    
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease-in';
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

function getNotificationIcon(type) {
    const iconMap = {
        'info': 'info-circle',
        'success': 'check-circle',
        'warning': 'exclamation-triangle',
        'error': 'times-circle'
    };
    return iconMap[type] || 'info-circle';
}

// 导出函数供HTML使用
window.switchEvaluationSection = switchEvaluationSection;
window.generateReport = generateReport;
window.exportSummary = exportSummary;
window.sendSurvey = sendSurvey;
window.createFollowUpTask = createFollowUpTask;
window.executeFollowUp = executeFollowUp;
window.editFollowUp = editFollowUp;
window.completeFollowUp = completeFollowUp;
window.loadMoreFollowUps = loadMoreFollowUps;
window.createSalesOpportunity = createSalesOpportunity;
window.goBackToActivity = goBackToActivity;